package com.ruoyi.project.system.order.order.controller;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.code.domain.ShopExpressCode;
import com.ruoyi.project.system.code.service.IShopExpressCodeService;
import com.ruoyi.project.system.coin.service.ICoinService;
import com.ruoyi.project.system.goods.product.domain.GoodsProduct;
import com.ruoyi.project.system.goods.product.service.IGoodsProductService;
import com.ruoyi.project.system.member.service.IMemberService;
import com.ruoyi.project.system.order.order.domain.OrderOrder;
import com.ruoyi.project.system.order.order.dto.OrderOrderDto;
import com.ruoyi.project.system.order.order.enums.OrderStatus;
import com.ruoyi.project.system.order.order.service.IOrderOrderService;
import com.ruoyi.project.system.order.ordergoods.dto.OrderGoodsDto;
import com.ruoyi.project.system.order.ordergoods.service.IOrderGoodsService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 订单Controller
 * 
 * @author LCL
 * @date 2020-06-18
 */
@Controller
@RequestMapping("/system/order")
public class OrderOrderController extends BaseController
{
    private String prefix = "system/order";

    @Autowired
    private IOrderOrderService orderOrderService;
    @Autowired
    private IOrderGoodsService orderGoodsService;
    @Autowired
    private IShopExpressCodeService shopExpressCodeService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private ICoinService coinService;
    @Autowired
    private IGoodsProductService goodsProductService;

    @RequiresPermissions("system:order:view")
    @GetMapping()
    public String order()
    {
        return prefix + "/order";
    }

    /**
     * 查询订单列表
     */
    @RequiresPermissions("system:order:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(OrderOrder orderOrder)
    {
        startPage();
        List<OrderOrderDto> list = orderOrderService.selectOrderOrderList(orderOrder);
        return getDataTable(list);
    }
    /**
     * 查询订单列表
     */
    @RequiresPermissions("system:order:list")
    @PostMapping("/goods")
    @ResponseBody
    public TableDataInfo goodsList(String orderId)
    {
        startPage();
        List<OrderGoodsDto> list = this.orderGoodsService.findListByOrderId(orderId);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @RequiresPermissions("system:order:export")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(OrderOrder orderOrder)
    {
        List<OrderOrderDto> list = orderOrderService.selectOrderOrderList(orderOrder);
        for(OrderOrderDto orderOrderDto:list){
            orderOrderDto.setStatusName(OrderStatus.getByValue(orderOrderDto.getStatus()).getName());
            OrderGoodsDto byUOrderId = this.orderGoodsService.findByUOrderId(orderOrderDto.getId());
            if (byUOrderId!=null) {
                orderOrderDto.setTotal(byUOrderId.getTotal());
                orderOrderDto.setGoodsName(byUOrderId.getGoodsName());
                orderOrderDto.setGoodsProductSpec(byUOrderId.getGoodsProductSpec());
            }
        }
        ExcelUtil<OrderOrderDto> util = new ExcelUtil<OrderOrderDto>(OrderOrderDto.class);
        return util.exportExcel(list, "order");
    }

    /**
     * 导出订单
     */
    @RequiresPermissions("system:order:export")
    @PostMapping("/exportExcel/{id}")
    @ResponseBody
    public AjaxResult exportExcel(@PathVariable String id) {
        OrderOrder orderOrder = orderOrderService.selectOrderOrderById(id);
        List<OrderOrderDto> list = orderOrderService.selectOrderOrderList(orderOrder);
        for(OrderOrderDto orderOrderDto:list){
            orderOrderDto.setStatusName(OrderStatus.getByValue(orderOrderDto.getStatus()).getName());
            OrderGoodsDto byUOrderId = this.orderGoodsService.findByUOrderId(orderOrderDto.getId());
            GoodsProduct productById = this.goodsProductService.selectGoodsProductById(byUOrderId.getProductId());
            if (byUOrderId!=null) {
                orderOrderDto.setTotal(byUOrderId.getTotal());
                orderOrderDto.setGoodsName(byUOrderId.getGoodsName());
                orderOrderDto.setGoodsProductSpec(byUOrderId.getGoodsProductSpec());
                orderOrderDto.setSku(productById.getSku());
            }
        }
        ExcelUtil<OrderOrderDto> util = new ExcelUtil<OrderOrderDto>(OrderOrderDto.class);
        return util.exportExcel(list, "order");
    }

    /**
     * 新增订单
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }
    /**
     * 查询订单详情
     */
    @GetMapping("/info/{id}")
    public String add(@PathVariable String id,ModelMap map)
    {
        map.put("order",this.orderOrderService.findByOrderId(id));
        return prefix + "/info";
    }
    /**
     * 查询订单发货详情
     */
    @GetMapping("/send/{id}")
    public String send(@PathVariable String id,ModelMap map)
    {
        map.put("order",this.orderOrderService.findByOrderId(id));
        map.put("expressList",this.shopExpressCodeService.findAll());
        return prefix + "/send";
    }
    /**
     * 订单发货
     */
    @RequiresPermissions("system:order:add")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("/send")
    @ResponseBody
    public AjaxResult sendSave(OrderOrder orderOrder)
    {
        orderOrder.setStatus(OrderStatus.TO_BE_RECEIVED.getValue());
        orderOrder.setConsignTime(DateUtils.getNowDate());
        orderOrder.setShippingCompanyCode(this.shopExpressCodeService.findByName(orderOrder.getShippingName()).getCode());
        this.orderOrderService.updateOrderOrder(orderOrder);
        return AjaxResult.success();
    }

    /**
     * 订单海关审核
     */
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("/customs/{id}")
    @ResponseBody
    public AjaxResult customs(@PathVariable String id)
    {
        OrderOrder order = new OrderOrder();
        order.setId(id);
        order.setStatus(OrderStatus.TO_BE_RECEIVED.getValue());
        this.orderOrderService.updateOrderOrder(order);
        return AjaxResult.success();
    }


    /**
     * 新增保存订单
     */
    @RequiresPermissions("system:order:add")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(OrderOrder orderOrder)
    {
        return toAjax(orderOrderService.insertOrderOrder(orderOrder));
    }

    /**
     * 修改订单
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        OrderOrder orderOrder = orderOrderService.selectOrderOrderById(id);
//        Coin byResId = coinService.findByResId(orderOrder.getOrderNo());
//
//        Member memberUser = memberService.selectMemberById(orderOrder.getUserId());
//        Member memberIntro = memberService.selectMemberById(memberUser.getIntroUser());
        mmap.put("orderOrder", orderOrder);
        mmap.put("expressList",this.shopExpressCodeService.findAll());
        mmap.put("member",this.memberService.selectMemberById(orderOrder.getUserId()));
//        if (byResId != null) {
//            mmap.put("priceP",byResId.getNum());
//        } else {
//            mmap.put("priceP",0);
//        }
//        if (memberIntro != null) {
//            mmap.put("memberIntro",memberIntro.getUsername());
//        } else {
//            mmap.put("memberIntro","无");
//        }
        return prefix + "/edit";
    }

    /**
     * 修改保存订单
     */
    @RequiresPermissions("system:order:edit")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(OrderOrder orderOrder)
    {
        OrderOrder oldOrder = this.orderOrderService.selectOrderOrderById(orderOrder.getId());
        if(oldOrder==null){
            return AjaxResult.error("找不到订单");
        }
        //判断是否修改物流信息 如果是 并且订单信息是待发货 就改为已发货
        if(!StringUtils.isBlank(orderOrder.getShippingName())){
            orderOrder.setConsignTime(DateUtils.getNowDate());
            orderOrder.setShippingCompanyCode(this.shopExpressCodeService.findByName(orderOrder.getShippingName()).getCode());
            if(oldOrder.getStatus().equals(OrderStatus.TO_BE_DELIVERED.getValue())){
                orderOrder.setStatus(OrderStatus.TO_BE_RECEIVED.getValue());
            }
        }
        return toAjax(orderOrderService.updateOrderOrder(orderOrder));
    }

    /**
     * 删除订单
     */
    @RequiresPermissions("system:order:remove")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(orderOrderService.deleteOrderOrderByIds(ids));
    }



    @PostMapping("/importExcel")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @ResponseBody
    @Transactional
    public R orderImport(MultipartFile file){
        if(file!= null) {
            String userExcelFileName = file.getOriginalFilename();
            //判断是否是Excel文件
            if(userExcelFileName.matches("^.+\\.(?i)((xls)|(xlsx))$"))
            {
                importExcel(file, userExcelFileName);
                return R.ok();
            }
            return R.error("文件类型错误");
        }
        return R.error("请选择文件");
    }


    public void importExcel(MultipartFile file, String excelFileName) {
        //1.创建输入流
        try {
            //FileInputStream inputStream = new FileInputStream(file);
            //boolean is03Excel = excelFileName.matches("^.+\\.(?i)(xls)$");
            //1.读取工作簿
            boolean is03Excel = excelFileName.matches("^.+\\.(?i)(xls)$");
            Workbook workbook = is03Excel?new HSSFWorkbook(file.getInputStream()):new XSSFWorkbook(file.getInputStream());
            //Workbook workbook = new HSSFWorkbook(file.getInputStream());
            //2.读取工作表
            Sheet sheet = workbook.getSheetAt(0);
            //3.读取行
            //判断行数大于一,是因为数据从第二行开始插入

            if(sheet.getPhysicalNumberOfRows() > 1) {
                //跳过前一行
                for(int k=1;k<sheet.getPhysicalNumberOfRows();k++ ) {
                    //读取单元格
                    Row row0 = sheet.getRow(k);
                    //订单编号
                    Cell cell0 = row0.getCell(0);
                    cell0.setCellType(Cell.CELL_TYPE_STRING);
                    String order_sn =cell0.getStringCellValue().replace("\t","").trim();
                    //物流公司名称
                    String shipping_name = "";
                    Cell cell9 = row0.getCell(1);
                    if (cell9 == null) {
                        shipping_name = "";
                    } else {
                        cell9.setCellType(Cell.CELL_TYPE_STRING);
                        shipping_name = cell9.getStringCellValue().replace("\t","").trim();
                    }
                    //物流单号
                    String shipping_code = "";
                    Cell cell10 = row0.getCell(2);
                    if (cell10 == null) {
                        shipping_code = "";
                    } else {
                        cell10.setCellType(Cell.CELL_TYPE_STRING);
                        shipping_code = cell10.getStringCellValue().replace("\t","").trim();
                    }
                    //物流公司编码
//                    String company_code = "";
//                    Cell cell3 = row0.getCell(3);
//                    if (cell10 == null) {
//                        company_code = "";
//                    } else {
//                        cell3.setCellType(Cell.CELL_TYPE_STRING);
//                        company_code = cell3.getStringCellValue().replace("\t","").trim();
//                    }
                    //单号查询订单信息
                    OrderOrderDto byOrderNo = this.orderOrderService.findByOrderNo(order_sn);
                    OrderOrder update = new OrderOrder();
                    update.setId(byOrderNo.getId());
                    update.setShippingCode(shipping_code);
                    ShopExpressCode byName = this.shopExpressCodeService.findByName(shipping_name);
                    if(byName!=null){
                        update.setShippingCompanyCode(byName.getCode());
                    }
                    update.setShippingName(shipping_name);
                    if(byOrderNo.getStatus().equals(OrderStatus.TO_BE_DELIVERED.getValue())){
                        update.setStatus(OrderStatus.TO_BE_RECEIVED.getValue());
                        update.setConsignTime(DateUtils.getNowDate());
                    }
                    this.orderOrderService.updateOrderOrder(update);
                }
            }
            workbook.close();
            //inputStream.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
